package com.yueyang.sojourn.server.service.member;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yueyang.sojourn.server.common.baymax.web.result.JAssert;
import com.yueyang.sojourn.server.model.enums.MemberStatus;
import com.yueyang.sojourn.server.model.enums.MemberUnit;
import com.yueyang.sojourn.server.model.po.Member;
import com.yueyang.sojourn.server.model.po.MemberMerch;
import com.yueyang.sojourn.server.model.po.MemberMerchSnap;
import com.yueyang.sojourn.server.model.po.SojournOrder;
import com.yueyang.sojourn.server.model.vo.SojournUserVo;
import com.yueyang.sojourn.server.service.sojourn.order.SojournOrderService;
import com.yueyang.sojourn.server.utils.PhoneNumberUtil;
import com.yueyang.uc.model.UcUserV1;
import com.yueyang.uc.spi.UserSpi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 会员service
 */
@Service
@Slf4j
public class MemberService {
    @Autowired
    private MemberMerchSnapService memberMerchSnapService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserSpi userSpi;
    @Autowired
    private MemberMerchService memberMerchService;
    @Autowired
    private SojournOrderService orderService;

    public Member findByUserId(Long userId) {
        return this.memberMapper.selectByPrimaryKey(userId);
    }



    /**
     * 更新会员信息 订单支付到账后回调
     */
    @Transactional
    public void paySuccessCallback(Long orderId) {
        log.info("开始会员支付成功回调");
        SojournOrder order = orderService.findById(orderId);
        JAssert.pass(order != null, "订单不存在");
        MemberMerch memberMerch = this.memberMerchService.findById(order.getMerchId().intValue());
        JAssert.pass(memberMerch != null, "订单中的会员信息不存在");
        Member member = this.findByUserId(order.getCreator());
        // 会员不存在 新建一个
        if (member == null) {
            member = new Member();
            member.setUserId(order.getCreator());
            member.setCtime(new Date());
            member.setMemberStatus(MemberStatus.会员.getValue());
            member.setMtime(new Date());
            member.setState((byte) 1);
            member.setStartTime(new Date());
            if (memberMerch.getUnit().equals(MemberUnit.YEAR.name())) {
                member.setExpiredTime(DateUtils.addYears(member.getStartTime(), memberMerch.getNum()));
            } else if (memberMerch.getUnit().equals(MemberUnit.MONTH.name())) {
                member.setExpiredTime(DateUtils.addMonths(member.getStartTime(), memberMerch.getNum()));
            } else if (memberMerch.getUnit().equals(MemberUnit.DAY.name())) {
                member.setExpiredTime(DateUtils.addDays(member.getStartTime(), memberMerch.getNum()));
            }
            this.memberMapper.insert(member);
        }

        // 如果存在会员信息，根据当前会员状态分别处理
        else {
            // 如果当前是会员，则累加当前会员过期时间
            if (member.getMemberStatus() == MemberStatus.会员.getValue()) {
                if (memberMerch.getUnit().equals(MemberUnit.YEAR.name())) {
                    member.setExpiredTime(DateUtils.addYears(member.getExpiredTime(), memberMerch.getNum()));
                } else if (memberMerch.getUnit().equals(MemberUnit.MONTH.name())) {
                    member.setExpiredTime(DateUtils.addMonths(member.getExpiredTime(), memberMerch.getNum()));
                } else if (memberMerch.getUnit().equals(MemberUnit.DAY.name())) {
                    member.setExpiredTime(DateUtils.addDays(member.getExpiredTime(), memberMerch.getNum()));
                }
            }
            // 已过期，则重新计算会员开始结束时间
            else if (member.getMemberStatus() == MemberStatus.已过期.getValue()) {
                member.setStartTime(new Date());
                if (memberMerch.getUnit().equals(MemberUnit.YEAR.name())) {
                    member.setExpiredTime(DateUtils.addYears(member.getStartTime(), memberMerch.getNum()));
                } else if (memberMerch.getUnit().equals(MemberUnit.MONTH.name())) {
                    member.setExpiredTime(DateUtils.addMonths(member.getStartTime(), memberMerch.getNum()));
                } else if (memberMerch.getUnit().equals(MemberUnit.DAY.name())) {
                    member.setExpiredTime(DateUtils.addDays(member.getStartTime(), memberMerch.getNum()));
                }
            }

            member.setMemberStatus(MemberStatus.会员.getValue());
            member.setMtime(new Date());
            this.memberMapper.updateByPrimaryKey(member);
        }

        this.memberMerchSnapService.snapshot(order.getMerchId().intValue(), orderId);
        log.info("会员支付成功回调结束");
    }

    /**
     * 判断是否是会员
     * @param userId
     * @return
     */
    public Boolean isMember(Long userId) {
        Member member = this.findByUserId(userId);
        return member != null && member.getMemberStatus().equals(MemberStatus.会员.getValue());
    }

    public PageInfo<SojournUserVo> findCustList(String keyword, Date regTimeStart, Date regTimeEnd, List<Byte> memberValues, List<Byte> sexValues, Integer pageSize, Integer pageNum) {
        Boolean member = null;
        if (CollectionUtils.isEmpty(memberValues) || (memberValues.contains((byte)1) && memberValues.contains((byte)0))) {
            member = null;
        }
        else {
            if (memberValues.contains((byte)1)) {
                member = true;
            } else if (memberValues.contains((byte)0)) {
                member = false;
            }
        }


        Boolean finalMember = member;
        PageInfo<SojournUserVo> pageInfo = PageHelper.startPage(pageNum, pageSize)
                .doSelectPageInfo(() -> this.userMapper.findCustList(keyword, regTimeStart, regTimeEnd, finalMember, CollectionUtils.isEmpty(sexValues) ? null : sexValues));
        pageInfo.getList().stream().forEach(sojournUserVo -> {
            sojournUserVo.setPhone(PhoneNumberUtil.getSecPhone(sojournUserVo.getPhone()));
        });
        return pageInfo;
    }

    public Long countCustAll() {
        return this.userMapper.countCustAll();
    }

    public SojournUserVo findDetail(Long userId) {
        UcUserV1 ucUserV1 = userSpi.findById(userId);
        JAssert.pass(ucUserV1 != null, "用户不存在,id=" + ucUserV1);
        SojournUserVo sojournUserVo = new SojournUserVo();
        BeanUtils.copyProperties(ucUserV1, sojournUserVo);
        sojournUserVo.setUserId(ucUserV1.getId());
        sojournUserVo.setPhone(PhoneNumberUtil.getSecPhone(sojournUserVo.getPhone()));
        this.fillMemberInfo(sojournUserVo);
        return sojournUserVo;
    }

    public void fillMemberInfo(SojournUserVo sojournUserVo) {
        Member member = this.findByUserId(sojournUserVo.getUserId());
        if (member != null) {
            sojournUserVo.setMember(member.getMemberStatus() == MemberStatus.会员.getValue());
            sojournUserVo.setMemberStatus(member.getMemberStatus());
            sojournUserVo.setMemberExpiredTime(member.getExpiredTime());
        } else {
            sojournUserVo.setMember(false);
            sojournUserVo.setMemberStatus(MemberStatus.不是.getValue());
        }
    }
}
